package us.icitap.cm.ui.policecase;

import java.util.Calendar;
import java.util.List;

import us.icitap.cm.CaseManagementUI;
import us.icitap.cm.business.entities.ActualSituation;
import us.icitap.cm.business.entities.AppEntity;
import us.icitap.cm.business.entities.EntityTypeEnum;
import us.icitap.cm.business.entities.Evidence;
import us.icitap.cm.business.entities.Evidence.EvidenceTypeEnum;
import us.icitap.cm.business.entities.Vehicle;
import us.icitap.cm.business.entities.regmin.Color;
import us.icitap.cm.business.entities.regmin.VehicleBrand;
import us.icitap.cm.business.entities.regmin.VehicleModel;
import us.icitap.cm.business.entities.regmin.VehicleType;
import us.icitap.cm.listeners.AppEntityListener;
import us.icitap.cm.ui.custom.CustBeanFieldGroup;
import us.icitap.cm.ui.custom.CustComboBox;
import us.icitap.cm.ui.custom.CustTextArea;
import us.icitap.cm.ui.custom.CustTextField;
import us.icitap.cm.ui.custom.CustomFormLayout;
import us.icitap.cm.ui.shared.AppEntityLayout;
import us.icitap.cm.utils.ProjectLists;
import us.icitap.utils.Result;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.AbstractSelect.ItemCaptionMode;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.VerticalLayout;

public class VehicleDataLayout extends AppEntityLayout{

	Vehicle vehicle;
	protected AppEntityListener listener;
	private final CustBeanFieldGroup<Vehicle> binder = new CustBeanFieldGroup<Vehicle>(Vehicle.class);
	
	final CustComboBox vehicleTypeSelect = new CustComboBox("Tipi");
	final CustComboBox vehicleBrandSelect = new CustComboBox("Marka");
	final CustComboBox vehicleModelSelect = new CustComboBox("Modeli");
	final CustComboBox prodYearSelect = new CustComboBox("Viti i prodhimit");
	final CustComboBox colorSelect = new CustComboBox("Ngjyra");
	final CustTextField vinTextField = new CustTextField("Nr. shasise");
	final CustTextField plateIdTextField = new CustTextField("Targa");
	final CustTextArea detailsTextArea = new CustTextArea("Detaje");
	final CustComboBox actualSituationSelect = new CustComboBox("Gjendja aktuale");
	final CheckBox registeredCheckBox = new CheckBox("E regjistruar");
	final CheckBox insuredCheckBox = new CheckBox("E siguruar");
	final CheckBox technicalTestedBox = new CheckBox("Me kontroll teknik");
	
	private final CheckBox evidenceCheckBox = new CheckBox("Eshte prove materiale");
	
	final CustomFormLayout cfl = new CustomFormLayout("600px", "Automjete te perfshira ne vendngjarje", "Reset", "Ruaj");	
	
	boolean editableVisible = false;
	boolean readOnlyVisible = false;

	private final EvidenceEmbeddableDataLayout evidenceEmbDataLayout = new EvidenceEmbeddableDataLayout();
	
	final TabSheet tabSheet = new TabSheet();
	
	
	public VehicleDataLayout() {
		this.setMargin(true);

		FormLayout fl0 = new FormLayout();
		fl0.addComponent(this.vehicleTypeSelect);
		fl0.addComponent(this.vehicleBrandSelect);
		fl0.addComponent(this.vehicleModelSelect);
		fl0.addComponent(this.colorSelect);
		fl0.addComponent(this.prodYearSelect);
		fl0.addComponent(this.vinTextField);
		fl0.addComponent(this.plateIdTextField);
		FormLayout fl1 = new FormLayout();
		fl1.setMargin(true);
		fl1.addComponent(this.detailsTextArea);
		fl1.addComponent(this.actualSituationSelect);
		fl1.addComponent(this.registeredCheckBox);
		fl1.addComponent(this.technicalTestedBox);
		fl1.addComponent(this.insuredCheckBox);
		fl1.addComponent(this.evidenceCheckBox);
		
		HorizontalLayout hl = new HorizontalLayout();
		hl.addStyleName("cmLayout");
		hl.setMargin(true);
		
		hl.addComponent(fl0);
		hl.addComponent(fl1);

		tabSheet.addTab(hl, "Te dhenat");

		cfl.addComponent(tabSheet);
		cfl.addFooter();
		detailsTextArea.setWidth("18em");
		
		
		vehicleTypeSelect.setContainerDataSource(new BeanItemContainer<VehicleType>(VehicleType.class, ProjectLists.getVehicleTypeList(false)));
		vehicleTypeSelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		vehicleTypeSelect.setItemCaptionPropertyId("tag");
		
		vehicleBrandSelect.setContainerDataSource(new BeanItemContainer<VehicleBrand>(VehicleBrand.class, ProjectLists.getVehicleBrandList(false)));
		vehicleBrandSelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		vehicleBrandSelect.setItemCaptionPropertyId("tag");
		
		
		vehicleModelSelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		vehicleModelSelect.setItemCaptionPropertyId("tag");
		
		colorSelect.setContainerDataSource(new BeanItemContainer<Color>(Color.class, ProjectLists.getColorList(false)));
		colorSelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		colorSelect.setItemCaptionPropertyId("tag");

		for (int i = Calendar.getInstance().get(Calendar.YEAR); i >= 1900; i--) {
			prodYearSelect.addItem(i);
		}
		
		actualSituationSelect.setContainerDataSource(new BeanItemContainer<ActualSituation>(ActualSituation.class, ProjectLists.getActualSituationList(false)));
		actualSituationSelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		actualSituationSelect.setItemCaptionPropertyId("tag");
		
		vehicleBrandSelect.setImmediate(true);
		
		vehicleBrandSelect.addValueChangeListener(new  ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				vehicleModelSelect.removeAllItems();
				System.out.println(vehicleBrandSelect.getValue());
				if(vehicleBrandSelect.getValue() != null){
					Result<List<VehicleModel>> result = CaseManagementUI.appStatelessBean.getPersistenceBean().getVehicleModel(vehicleBrandSelect.getValue());
					if(result.isSucceeded() && result.getObject() != null && !result.getObject().isEmpty()){
						vehicleModelSelect.setContainerDataSource(new BeanItemContainer<VehicleModel>(VehicleModel.class, result.getObject()));
						
					}
				}
			}
		});
		
		cfl.addRightClickListener(new ClickListener() {
			
			@Override
			public void buttonClick(ClickEvent event) {
				try {
					binder.commit();
					if(VehicleDataLayout.this.listener != null){
						if(oldAppEntity == null){
							if((evidenceCheckBox.getValue().booleanValue())){
								vehicle.getAppEntity().setEvidence(evidenceEmbDataLayout.getEvidence());	
							}
							VehicleDataLayout.this.listener.addAppEntityToReport(vehicle.getAppEntity());
						}
						else{
							//Eshte entitet ekzistues
							System.out.println("Eshte entitet ekzistues");
							if(!oldAppEntity.getVehicle().myEquals(vehicle)){
								//Entiteti ka ndryshuar
								
								if(vehicle.getAppEntity().getEvidence() != null && 
										vehicle.getAppEntity().getEvidence().myEquals(oldAppEntity.getEvidence())){
									//Nuk ka ndryshuar prova");
									vehicle.getAppEntity().setEvidence(oldAppEntity.getEvidence());
								}
								vehicle.getAppEntity().setRecordUser(CaseManagementUI.getUser().getUsername());
								VehicleDataLayout.this.listener.updateAppEntityIntoReport(oldAppEntity, vehicle.getAppEntity());
							}
							else
							{
								//Entiteti nuk k ndryshuar, as prova
//								oldAppEntity.replaceEntityReportAssociationList(vehicle.getAppEntity().getReportAssociationList());
								VehicleDataLayout.this.listener.refresh(oldAppEntity);
							}
							
							addAppEntity();
						}
							
							
						
						
					}
				} catch (CommitException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
		
		binder.bind(this.vehicleTypeSelect, "vehicleType");
		binder.bind(this.vehicleBrandSelect, "vehicleBrand");
		binder.bind(this.vehicleModelSelect, "vehicleModel");
		binder.bind(this.colorSelect, "color");
		binder.bind(this.prodYearSelect, "productionYear");
		binder.bind(this.vinTextField, "vin");
		binder.bind(this.plateIdTextField, "plateId");
		binder.bind(this.actualSituationSelect, "actualSituation");
		binder.bind(this.detailsTextArea, "details");
		binder.bind(this.insuredCheckBox, "insured");
		binder.bind(this.registeredCheckBox, "registered");
		binder.bind(this.technicalTestedBox, "technicalTested");
		
		evidenceCheckBox.setImmediate(true);
		evidenceCheckBox.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				if(evidenceCheckBox.getValue().booleanValue()){
					// Entiti shoqerohet me prove
					tabSheet.addTab(evidenceEmbDataLayout, "Prove materiale");
					
					if(oldAppEntity != null && oldAppEntity.getEvidence() != null){
						// Entiteti ekzistues ka prove ekzistuese te lidhur me te
						vehicle.getAppEntity().setEvidence(new Evidence(oldAppEntity.getEvidence()));
						evidenceEmbDataLayout.loadEvidence(vehicle.getAppEntity().getEvidence(),true);
					}
					else{
						// Entiteti ekzistues nuk ka prove ekzistues te lidhur me te
						// Krijohet prove e re 
						evidenceEmbDataLayout.createEvidence(EvidenceTypeEnum.MATERIAL);
					}
				}
				else{
					// Entiteti nuk ka prove ekzistuese te lidhur me te
					vehicle.getAppEntity().setEvidence(null);
					tabSheet.removeComponent(evidenceEmbDataLayout);	
				}
			}
		});
		
	}
	
	public void showEditableForm(){
		if(editableVisible) return ;
		
		this.removeAllComponents();
		this.addComponent(cfl);
		
		editableVisible = true;
		readOnlyVisible = false;
	}
	

	public void showReadOnlyForm(){
		if(readOnlyVisible) return;
		this.removeAllComponents();
		VerticalLayout vl = ViewCaseLayout.showVehicle(vehicle);
		vl.setCaption(EntityTypeEnum.DOCUMENT.getCaption());
		this.addComponent(vl);
		editableVisible = false;
		readOnlyVisible = true;
	}

	@Override
	public void addAppEntity() {
		this.tabSheet.setSelectedTab(0);
		AppEntity appEntity = new AppEntity(CaseManagementUI.getUser().getUsername(), EntityTypeEnum.VEHICLE);
		vehicle = appEntity.getVehicle();
		binder.setItemDataSource(vehicle);

		this.showEditableForm();

	}
	
	@Override
	public void addAppEntityListener(AppEntityListener listener) {
		this.listener = listener;
		
	}

	private AppEntity oldAppEntity;
	
	@Override
	public void loadAppEntity(AppEntity appEntity, boolean editable) {

		oldAppEntity = appEntity;
		
		AppEntity newAppEntity = new AppEntity(appEntity);
		
		this.vehicle = newAppEntity.getVehicle();
		binder.setItemDataSource(vehicle);
		
		if(newAppEntity.getEvidence()!= null){
			evidenceCheckBox.setValue(new Boolean(true));
			evidenceEmbDataLayout.loadEvidence(newAppEntity.getEvidence(), true);
			tabSheet.addTab(evidenceEmbDataLayout, "Prove materiale");
		}
		else{
			evidenceCheckBox.setValue(new Boolean(false));
		}
		
		if(editable) 
			this.showEditableForm();
		
		else
			this.showReadOnlyForm();
	
	}

}
